package com.ywjt.platformbusiness.market.integralgoods.fragment;

import android.content.Context;
import android.os.Build;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.ywjt.platformbusiness.R;
import com.ywjt.platformbusiness.base.BaseVPFragment;
import com.ywjt.platformbusiness.constants.Constants;
import com.ywjt.platformbusiness.constants.UrlConstants;
import com.ywjt.platformbusiness.http.HttpRequest;
import com.ywjt.platformbusiness.http.HttpStringCallBack;
import com.ywjt.platformbusiness.market.hagglegoods.activity.HaggleGoodsDetail;
import com.ywjt.platformbusiness.market.hagglegoods.activity.HaggleMallActivity;
import com.ywjt.platformbusiness.market.hagglegoods.adapter.HaggleGoodsAdapter;
import com.ywjt.platformbusiness.market.hagglegoods.model.GroupListModel;
import com.ywjt.platformbusiness.market.integralgoods.activity.IntegralGoodsDetail;
import com.ywjt.platformbusiness.market.integralgoods.activity.IntegralMallActivity;
import com.ywjt.platformbusiness.market.integralgoods.adapter.IntegralGoodsFragmentAdapter;
import com.ywjt.platformbusiness.market.integralgoods.model.IntegralListModel;
import com.ywjt.platformbusiness.util.JsonUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

public class IntegralGoodsFragment extends BaseVPFragment {
    private Context context;
    private List<IntegralListModel.ResultDTO.RecordsDTO> datas;
    private RecyclerView rcGoods;
    private LinearLayout llNodata;
    private SmartRefreshLayout refresh;
    private IntegralGoodsFragmentAdapter goodsAdapter;
    private int currentPage=1;
    private int count=0;
    private String classId="";

    public static IntegralGoodsFragment newInstance(String classId) {
        Bundle arguments = new Bundle();
        arguments.putString("classId",classId);
        IntegralGoodsFragment fl = new IntegralGoodsFragment();
        fl.setArguments(arguments);
        return fl;
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view=inflater.inflate(R.layout.goods_type_fragment,container,false);
        initView(view);
        return view;
    }


    @Override
    protected void onFragmentVisibleChange(boolean isVisible) {

    }


    public void initView(View view){
        classId=getArguments().getString("classId");
        context=getActivity();
        llNodata= view.findViewById(R.id.llNodata);
        refresh=view.findViewById(R.id.refresh);
        rcGoods=view.findViewById(R.id.rcCommon);
        setView();

    }

    /**
     * 在fragment首次可见时回调，可用于加载数据，防止每次进入都重复加载数据
     */
    @Override
    protected void onFragmentFirstVisible() {
        getGoods();
    }

    public void setView(){
        datas=new ArrayList<>();
        refresh.setEnableAutoLoadMore(true);//开启自动加载功能（非必须）
        refresh.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(final RefreshLayout refreshLayout) {
                refreshLayout.getLayout().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        currentPage = 1;
                        getGoods();
                    }
                }, 1000);
            }
        });
        refresh.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull final RefreshLayout refreshLayout) {
                refreshLayout.getLayout().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        currentPage++;
                        getGoods();
                    }
                }, 1000);
            }
        });
    }


    public void getGoods(){
        JSONObject jsonObject=new JSONObject();
        try {
            jsonObject.put("classId",classId);
            jsonObject.put("pageNum", currentPage);
            jsonObject.put("pageSize", 2);// Constants.PAGESIZE
           // jsonObject.put("lngStr","113.784208,34.758762");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        new HttpRequest(getContext()).doPost(UrlConstants.getCommodityIntegralList, "",jsonObject, new HttpStringCallBack() {
            @RequiresApi(api = Build.VERSION_CODES.M)
            @Override
            public void onSuccess(Object result) {

                String data = result.toString();
                //把请求得数据转换成json对象
                JSONObject jsonObject = null;
                try {
                    jsonObject = new JSONObject(data);
                    String message = jsonObject.getString("message");
                    Boolean success=jsonObject.getBoolean("success");
                    if(success){
                        Object obj = JsonUtils.fromJson(result.toString(), IntegralListModel.class);
                        if (obj instanceof IntegralListModel) {
                            IntegralListModel model = (IntegralListModel) obj;
                            if (currentPage == 1) {
                                datas.clear();
                                count = model.getResult().getTotal();
                                if (model.getResult().getRecords().size() > 0) {
                                    datas=model.getResult().getRecords();
                                    llNodata.setVisibility(View.GONE);
                                    rcGoods.setVisibility(View.VISIBLE);
                                    goodsAdapter=new IntegralGoodsFragmentAdapter(datas);
                                    rcGoods.setLayoutManager(new GridLayoutManager(context,2,RecyclerView.VERTICAL,false));
                                    rcGoods.setAdapter(goodsAdapter);
                                    goodsAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
                                        @Override
                                        public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                                            IntegralGoodsDetail.actionStart(context,datas.get(position).getId());
                                        }
                                    });
                                    if (goodsAdapter.getItemCount() < count) {
                                        //还有多的数据
                                        refresh.finishRefresh();
                                    } else {
                                        //没有更多数据（上拉加载功能将显示没有更多数据）
                                        refresh.finishRefreshWithNoMoreData();
                                    }
                                } else {
                                    refresh.finishRefreshWithNoMoreData();
                                    llNodata.setVisibility(View.VISIBLE);
                                    rcGoods.setVisibility(View.GONE);
                                }
                            } else {
                                datas.addAll(model.getResult().getRecords());
                                goodsAdapter.notifyDataSetChanged();
                                if (goodsAdapter.getItemCount() < count) {
                                    //还有多的数据
                                    refresh.finishRefresh();
                                } else {
                                    //没有更多数据（上拉加载功能将显示没有更多数据）
                                    refresh.finishRefreshWithNoMoreData();
                                }
                            }
                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(int code, String msg) {
            }
        });
    }
}
